/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.oauth.services;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.koorz.constant.GlobalConstant;
import com.koorz.modules.user.PartyAccount;
import com.koorz.modules.user.User;
import com.koorz.oauth.model.OAuthConstants;
import com.koorz.oauth.model.OAuthRequest;
import com.koorz.oauth.model.Response;
import com.koorz.oauth.model.Token;
import com.koorz.oauth.model.UserWrapper;
import com.koorz.oauth.model.Verb;
import com.koorz.oauth.model.renren.RenrenToken;
import com.koorz.utils.FileUtil;
import com.koorz.utils.IdManage;
import com.koorz.utils.LoginUtil.WeiboType;


/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-4-8 下午6:45:23
 * 版  本  号：1.0
 */
public class RenrenService extends ApiService{

	private String API_URL_PREFIX = "https://api.renren.com/restserver.do";
	
	public UserWrapper getUserInfo(String accessToken) {
		OAuthRequest request = createRequest(Verb.POST, API_URL_PREFIX);
		request.addBodyParameter("method", "users.getInfo");
		request.addBodyParameter("format", "json");
		request.addBodyParameter("v", "1.0");
		request.addBodyParameter("fields","uid,name,sex,birthday,headurl,tinyurl,city,description,hometown_location");
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONArray jsonArray = JSON.parseArray(response.getBody());
	    	return wapperUser(jsonArray.getJSONObject(0));
	    }
	    return null;
	}

	@Override
	protected UserWrapper wapperUser(JSONObject obj) {
		UserWrapper user = new UserWrapper();
		if(obj.containsKey("id")){
			user.setUid(obj.getString("id"));
		}
		if(obj.containsKey("uid")){
			user.setUid(obj.getString("uid"));
		}
		if(obj.containsKey("tinyurl_with_logo")){
			user.setAvatar(obj.getString("tinyurl_with_logo"));
		}
		if(obj.containsKey("tinyurl")){
			user.setAvatar(obj.getString("tinyurl"));
		}
		if(obj.containsKey("headurl_with_logo")){
			user.setAvatarLarge(obj.getString("headurl_with_logo"));
		}
		if(obj.containsKey("headurl")){
			user.setAvatarLarge(obj.getString("headurl"));
		}
		if(obj.containsKey("description")){
			user.setDesc(obj.getString("description"));
		}
		if(obj.containsKey("sex")){
			user.setGender(obj.getIntValue("sex"));
		}
		if(obj.containsKey("city")){
			user.setLoc(obj.getString("city"));
		}
		if(obj.containsKey("name")){
			user.setNickname(obj.getString("name"));
		}
		return user;
	}

	@Override
	protected List<UserWrapper> wapperUsers(JSONArray array) {
		List<UserWrapper> users = new ArrayList<UserWrapper>();
		 for(int i=0;i<array.size();i++){
			 JSONObject userObj = array.getJSONObject(i);
			 users.add(wapperUser(userObj));
		 }
		 return users;
	}

	@Override
	public User bindUser(Token objClass) {
		RenrenToken accessToken = (RenrenToken) objClass;
		UserWrapper userWrapper = getUserInfo(accessToken.getAccessToken());
		User user = User.dao.findFirst("select u.id from user as u inner join party_account as pa on pa.user_id=u.id where pa.account_id=?",userWrapper.getUid());		
		if (user == null) {
			user = new User();
			String userId = IdManage.nextId(IdManage.USER);
			user.set("id", userId);
			user.set("nickname",userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature",userWrapper.getDesc());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.set("created_time", new Timestamp(Calendar.getInstance().getTimeInMillis()));
			user.set("score", 0);
			user.set("used_disk", 0);
			user.set("ranking", 0);
			user.set("upload_imitative_num", 0);
			user.set("upload_original_num", 0);
			user.set("upload_other_num", 0);
			user.set("artist_rate", 0.0);
			user.set("agents_rate", 0.0);
			user.set("singer_name", userWrapper.getNickname());
			user.set("region", userWrapper.getLoc());
			user.set("description", userWrapper.getDesc());
			user.set("user_website",GlobalConstant.DOMAIN_HOST + "/" + userId);
			user.set("tel", "");
			user.set("email", "");
			user.set("grade_id", "000000");
			//user.set("user_type",UserType.SELF.ordinal());
			user.save();
			
			PartyAccount account = new PartyAccount();
			account.set("id", IdManage.nextId(IdManage.PARTYACCOUNT));
			account.set("user_id", userId);
			account.set("account_id", userWrapper.getUid());
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", accessToken.getRefreshToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.set("type", WeiboType.RENREN.ordinal());
			account.save();
//			for(int i=0;i<GlobalConstant.DEFAULTIMGS.length;i++){
//				ArtistsCover cover = new ArtistsCover();
//				cover.set("id", IdManage.nextId(IdManage.COVER));
//				cover.set("user_id", user.getStr("id"));
//				cover.set("img_url", GlobalConstant.DEFAULTIMGS[i]);
//				cover.set("is_show", 1);
//				cover.set("time", DateUtil.getNowDateTime());
//				cover.set("type", 0);
//				cover.save();
//			}
			
//			Db.update("insert into user_weibo_setting values(?,?,?,?,?,?)", 
//					IdManage.nextId(IdManage.USER_WEIBO_SETTING),
//					userId,WeiboType.RENREN.ordinal(),1,1,1);
			user.put("grade_name", "流浪歌手");
			user.put("grade_level", "Lv1");
			user.put("platform",WeiboType.RENREN.ordinal());
		} else {
			user.set("nickname",userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature",userWrapper.getDesc());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.update();
			
			PartyAccount account = PartyAccount.dao.findFirst("select id,user_id,access_token,expires_in from party_account where user_id=? and account_id=?", 
					new Object[]{user.getStr("id"),userWrapper.getUid()});
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", accessToken.getRefreshToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.update();
			
			user = User.dao.findFirst("select u.id,u.avatar,u.avatar_large,u.nickname,u.midou,u.user_website,u.score,u.ranking,g.name as grade_name,g.level as grade_level from user as u " +
						" inner join grade as g on g.id=u.grade_id " +
						" where u.id=?",user.getStr("id"));
			user.put("platform",WeiboType.RENREN.ordinal());
		}
		return user;
	}
	
	/**
	 * 
	 * 功能描述：获取好友列表
	 * 作        者：尹东东
	 * 创建时间：2013-4-20 下午1:42:07
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public Page<UserWrapper> getUserFollowers(String accessToken,int page, int count) {
		OAuthRequest request = createRequest(Verb.POST, API_URL_PREFIX);
		request.addBodyParameter("method","friends.getFriends");
		request.addBodyParameter("format", "json");
		request.addBodyParameter("v", "1.0");
		request.addBodyParameter("page",page+"");
		request.addBodyParameter("count",count+"");
		request.addBodyParameter("fields","id,name,headurl_with_logo,tinyurl_with_logo");
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONArray usersJson = JSON.parseArray(response.getBody());
			if(usersJson.size() > 0){
				return new Page<UserWrapper>(wapperUsers(usersJson),page,count,page,count);
			}
	    }
	    return new Page<UserWrapper>(new ArrayList<UserWrapper>(0),page,count,0,0);
	}
	
	/**
	 * 
	 * 功能描述：邀请好友
	 * 作        者：尹东东
	 * 创建时间：2013-4-20 下午1:58:28
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public int inviteFriend(String accessToken,String status,String atUser) {
		String inviteFriendTemplate = "我正在用%s。%s";
		OAuthRequest request = createRequest(Verb.POST,API_URL_PREFIX);
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		request.addBodyParameter("format", "json");
		request.addBodyParameter("v", "1.0");
		request.addBodyParameter("method", "notifications.send");
		request.addBodyParameter("notification",String.format(inviteFriendTemplate,GlobalConstant.DOMAIN_HOST,status));
		request.addBodyParameter("to_ids",atUser);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}
	
	/**
	 * 
	 * 功能描述：分享微博
	 * 作        者：尹东东
	 * 创建时间：2013-4-20 下午2:06:06
	 * 参       数：uid人人站内用户id，username歌曲用户名，url歌曲拥有者链接
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public int shareStatus(String accessToken, String name,String description,String message,String url,String image) {
		OAuthRequest request = createRequest(Verb.POST,API_URL_PREFIX);
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		request.addBodyParameter("format", "json");
		request.addBodyParameter("v", "1.0");
		
		request.addBodyParameter("method", "feed.publishFeed");
		request.addBodyParameter("name",name);//新鲜事标题 注意：最多30个字符
		request.addBodyParameter("description",description);//新鲜事主体内容 注意：最多200个字符。
		request.addBodyParameter("message",message);//用户输入的自定义内容。注意：最多200个字符。
		request.addBodyParameter("url",url);//新鲜事标题和图片指向的链接。
		request.addBodyParameter("image",image);//新鲜事标题和图片指向的链接。
		
//		request.addBodyParameter("method", "share.share");
//		request.addBodyParameter("type","11");
//		request.addBodyParameter("user_id",uid);
//		request.addBodyParameter("url",url);
//		request.addBodyParameter("comment",status);
//		JSONObject obj = new JSONObject();
//		obj.put("text", "♫ "+songName+" - miri.fm");
//		obj.put("href", GlobalConstant.DOMAIN_HOST);
//		request.addBodyParameter("source_link",obj.toJSONString());
	    Response response = request.send();
	    //IOUtils.readLines(response.getStream()).toString()
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}
	
	public static void main(String[] args) {
		RenrenService service = new RenrenService();
		String accessToken = "230358|6.d44b80bfd1edcf3ddc792b2bd7505ff6.2592000.1369501200-236659155";
		String uid = "236659155";
		//service.getUserInfo(accessToken);
		//service.inviteFriend(accessToken, "好好ting", uid);
		String name = "♫ 冰雨 - 刘德华 - Miri.fm";
		String description = "MIRI.FM-创作自己的音乐电台";
		String message = "我分享了 刘德华  的歌曲 ♫冰雨 ，快来听听吧。";
		String url = GlobalConstant.DOMAIN_HOST+"/100065";
		String image = "http://static.miri.fm/101149/avatar/dcb155489e3a4961b748b566b7a53859.jpeg";
		service.shareStatus(accessToken, name, description,message,url,image);
	}
}
